import axios from 'axios'

const instance = axios.create()
//  http request 拦截器
instance.interceptors.request.use(
	config => {
		config.headers = {
			'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
		}
		return config
	},
	error => {
		return Promise.reject(error)
	}
)

// http response 拦截器
instance.interceptors.response.use(
	response => {
		return response
	},
	error => {
		return Promise.reject(error)
	}
)

// GET
export function get(url, params = {}) {
	return new Promise((resolve, reject) => {
		instance.get(url, { params: params })
			.then(response => {
				return resolve(response.data)
			})
			.catch(err => {
				return reject(err)
			})
	})
}

// POST
export function post(url, data = {}) {
	return new Promise((resolve, reject) => {
		instance.post(url, data).then(
			response => {
				return resolve(response.data)
			},
			err => {
				return reject(err)
			}
		)
	})
}

// DELETE
export function del(url, params = {}) {
	return new Promise((resolve, reject) => {
		instance.delete(url, { data: params }).then(
			response => {
				return resolve(response.data)
			},
			err => {
				return reject(err)
			}
		)
	})
}

// PUT
export function put(url, data = {}) {
	return new Promise((resolve, reject) => {
		instance.put(url, data).then(
			response => {
				resolve(response.data)
			},
			err => {
				reject(err)
			}
		)
	})
}

export default instance
